import puppeteer from 'puppeteer-core';
import * as cheerio from 'cheerio';
// 添加日志服务导入
import { LogService } from '../libs/log/log.service';

// 修改函数签名，接受日志服务
export async function spiderBaiduAi(word: string, maxRetries: number = 3, logger?: LogService) {
  let attempt = 0;

  while (attempt < maxRetries) {
    attempt++;
    const message = `${word}：第${attempt}次尝试执行`;
    if (logger) {
      logger.info(message);
    } else {
      console.log(message);
    }

    const browser = await puppeteer.launch({
      executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe',
      headless: true,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-accelerated-2d-canvas',
        '--no-first-run',
        '--no-zygote',
        '--disable-gpu',
      ],
    });
    const page = await browser.newPage();

    // 设置 User-Agent 模拟真实浏览器
    await page.setUserAgent(
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    );

    // 设置其他浏览器特征
    await page.setViewport({ width: 1366, height: 768 });
    await page.setExtraHTTPHeaders({
      'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
      Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    });

    try {
      // 访问网站
      await page.goto(`https://chat.baidu.com/search?word=${word}`, {
        waitUntil: 'networkidle2',
        timeout: 4 * 60 * 1000,
      });

      // 获取页面标题
      const title = await page.title();
      const titleMessage = `✅ 页面标题: ${title}`;
      if (logger) {
        logger.info(titleMessage);
      } else {
        console.log(titleMessage);
      }

      // 等待30秒
      await page.waitForSelector('div[data-module="ai_questionClosely"]', {
        timeout: 4 * 60 * 1000,
      });

      // 获取页面HTML
      const html = await page.content();
      const content = solveContent(html, logger);

      await browser.close();

      // 如果成功获取到内容，直接返回
      if (content && content.length > 0) {
        const successMessage = `${word}：第${attempt}次尝试成功`;
        if (logger) {
          logger.info(successMessage);
        } else {
          console.log(successMessage);
        }
        return content;
      } else {
        throw new Error('未获取到有效内容');
      }
    } catch (error) {
      const errorMessage = `第${attempt}次尝试失败: ${error.message}`;
      if (logger) {
        logger.error(errorMessage);
      } else {
        console.error(errorMessage);
      }
      await browser.close();

      // 如果不是最后一次尝试，等待一段时间再重试
      if (attempt < maxRetries) {
        const retryMessage = `等待2秒后进行第${attempt + 1}次重试...`;
        if (logger) {
          logger.info(retryMessage);
        } else {
          console.log(retryMessage);
        }
        await new Promise((resolve) => setTimeout(resolve, 2000));
      }
    }
  }

  const finalMessage = `${word}：所有${maxRetries}次尝试都失败了`;
  if (logger) {
    logger.error(finalMessage);
  } else {
    console.log(finalMessage);
  }
  return '';
}

function solveContent(html: string, logger?: LogService) {
  const $ = cheerio.load(html);

  const messageContent = $('.marklang').last();

  if (messageContent.length > 0) {
    const text = messageContent.text().trim().replace(/\s/g, '');
    return text;
  } else {
    const message = '未找到目标元素';
    if (logger) {
      logger.warn(message);
    } else {
      console.log(message);
    }
    return '';
  }
}
